package com.neo.agent.connection;

import com.alibaba.fastjson.JSON;

import javax.websocket.EndpointConfig;
import javax.websocket.OnOpen;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * Created by lock on 17-8-1.
 */

@ServerEndpoint("/connections")
public class ConnectionController  {

    private ConnectionService connectionService;
    private RemoteEndpoint.Basic remote;
    private ConnectionRenderListener remoteRender;


    @OnOpen
    public void onOpen(Session session, EndpointConfig config){
        connectionService = (ConnectionService) SpringBeanUtils.getBeans("mongoConnectionListener");
        remote = session.getBasicRemote();
        remoteRender = connectionInfos -> sendMessage(JSON.toJSONString(connectionInfos));
        connectionService.bindingConnectionClosed(remoteRender);
        connectionService.bindingConnectionRegister(remoteRender);
        sendMessage(JSON.toJSONString(connectionService.loadAllConnection()));
    }




    private void sendMessage(String text){
        try {
            remote.sendText(text);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }







}
